<?php
/**
 * Description of PostFacade
 *
 * @author TheFaSTeR
 */
class PostFacade
{
    
    public static function getPostsByUser($userId)
    {
        return BlogPost::model()->findAll('user_id=:user', array(':user' => $userId));        
    }    
    
    public static function getLatestPostsByUser($userId)
    {
        return BlogPost::model()->latest()->findAll('user_id=:user', array(':user' => $userId));        
    }
    
    public static function getPostsCountByUser($userId)
    {
        return BlogPost::model()->count('user_id=:user', array(':user' => $userId));
    }

    public static function getRandPosts($count)
    {
        $criteria = new CDbCriteria();
        $criteria->order = "rand()";
        $criteria->limit = $count;
        $post = Post::model()->findAll($criteria);
        return $post;
    }

    public static function saveModel(BlogPost $model)
    {
        $isNewRecord = $model->isNewRecord;
        $success = true;
        if ($isNewRecord)
        {
            $commentFlow = new CommentFlow;
            $success &= $commentFlow->save();
            $model->comment_flow_id = $commentFlow->comment_flow_id;
        }
        $success &= $model->save();
        return $success;
    }

    public static function deleteModel($postId)
    {
        $post = PostFacade::loadModel($postId);
        $commentFlowId = $post->comment_flow_id;
        $post->comment_flow_id = NULL;
        $post->save();
        CommentFacade::deleteCommentFlowModel($commentFlowId);
        $post->delete();
    }

    public static function loadModel($id)
    {
        $model = BlogPost::model()->findByPk( ( int ) $id );
        if ( $model === null )
            throw new CHttpException( 404, 'The requested page does not exist.' );
        return $model;
    }

    public static function getDataProviderForSearch($title)
    {
        $criteria = new CDbCriteria();
        if (!empty($title ))
            $criteria->addSearchCondition( 'title', $title, true, 'OR' );
        $dataProvider = new CActiveDataProvider( 'BlogPost', array( 'criteria' => $criteria, ) );
        return $dataProvider;
    }

}
